﻿using System.Collections.Generic;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;

namespace RGB.SharePoint.SPEasyCopy
{
    class Utility
    {
        public static List<FolderInfo> GetFoldersInFolder(SPFolder folder)
        {
            List<FolderInfo> result = new List<FolderInfo>();
            FolderInfo folderinfo;
            SPFolderCollection subFolders = folder.SubFolders;
            foreach (SPFolder subFolder in subFolders)
            {
                folderinfo = new FolderInfo();
                folderinfo.ID = subFolder.UniqueId;
                folderinfo.Name = subFolder.Name;
                folderinfo.URL = subFolder.Url;
                result.Add(folderinfo);
            }
            return result;
        }

        public static TreeNode GetFolderNode(TreeNode node, SPFolder folder, string baseURL, SPUser user)
        {
            List<FolderInfo> folders = GetFoldersInFolder(folder);
            folders.Sort(new FolderInfoComparer(SortDirection.Ascending));
            TreeNode folderNode;
            SPDocumentLibrary docLib = folder.DocumentLibrary;
            for (int j = 0; j <= folders.Count - 1; j++)
            {
                if (folders[j].Name != "Forms" && docLib.Folders[folders[j].ID].DoesUserHavePermissions(user, SPBasePermissions.AddListItems))
                {
                    folderNode = new TreeNode();
                    folderNode.ImageUrl = baseURL + "/_layouts/images/folder.gif";
                    folderNode.Text = folders[j].Name;
                    folderNode.NavigateUrl = "javascript:void(0)";
                    folderNode.ToolTip = baseURL + "/" + folders[j].URL;
                    SPFolder subfolder = folder.SubFolders[folders[j].URL];
                    folderNode.ChildNodes.Add(GetFolderNode(folderNode, subfolder, baseURL, user));
                    node.ChildNodes.Add(folderNode);
                }
            }
            return node;
        }
    }
}
